package io.github.wslxm.springbootplus2.starter.robot.api;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import io.github.wslxm.springbootplus2.starter.robot.properties.WebhookProperties;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 企业微信群机器人
 *
 * @author wangsong
 * @date 2023/05/17
 */
public class WechatApi {

    /**
     * 发送信息
     *
     * @param  webhookProperties
     * @param  content
     *      <p>
     *       contentMap 如下:
     *         "text": {
     *             "content": "广州今日天气：29度，大部分多云，降雨概率：60%",
     *             "mentioned_list":["wangqing","@all"],
     *             "mentioned_mobile_list":["13800001111","@all"]
     *         }
     *      <p/>
     */
    public static String sendMsg(WebhookProperties webhookProperties, String content) {
        // 具体消息 text 组装
        Map<String, Object> wechatContentMap = new HashMap<>(4);
        wechatContentMap.put("content", content);
        String mobiles = webhookProperties.getDefaultAtUser();
        if (mobiles != null && !"".equals(mobiles)) {
            wechatContentMap.put("mentioned_mobile_list", Arrays.asList(mobiles.split(",")));
        }
        // 发送消息本体组装
        Map<String, Object> paramMap = new HashMap<>(4);
        paramMap.put("msgtype", "text");
        paramMap.put("text", wechatContentMap);
        // 请求
        return HttpRequest.post(webhookProperties.getUrl())
                .header("Content-Type", "application/json;charset=utf-8")
                .body(JSON.toJSONString(paramMap))
                .execute().body();
    }
}
